package com.wan.activity;

import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import net.sourceforge.simcpux.Util;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wan.activity.util.Base64;
import com.wan.commonsdk.Conet;
import com.wan.commonsdk.MD5Utils;
import com.wan.commonsdk.PayInfo;
import com.wan.commonsdk.YHQInfo;
import com.wan.task.PayYHQTask;
import com.wan.taskListener.PayOrderYHQTaskListener;

public class WanYHListActivity extends BaseActivity implements
		OnItemClickListener, OnClickListener {
	private ListView mListView;
	private ArrayList<YHQInfo> list;
	private PayInfo payInfo;
	private Button yhlist_dh_btn;
	private EditText yhq_edit_code;
	private String yhq_code;
	private TextView yhqlist_back_btn, yhq_rule_tx;
	YHlistAdapter listAdapter;
	private TextView wan51_yhqlist_tx;
	
	private View footerView;
	private String other = "0";
	private TextView footer_tx;
	ProgressBar wan_footer_pro;
	
	int page = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(Util.getResID("wan51_yhlist_activity", "layout"));
		init();
	}

	private void init() {
		Intent intent = getIntent();
		payInfo = (PayInfo) intent.getSerializableExtra("payinfo");
		list = (ArrayList<YHQInfo>) intent.getSerializableExtra("list");

		mListView = (ListView) findViewById(Util.getResID("yhlist_list", "id"));
		wan51_yhqlist_tx = (TextView) findViewById(Util.getResID("wan51_yhqlist_tx","id"));
		footerView = View.inflate(this, Util.getResID("wan51_order_listfooter", "layout"), null);
	
		if (list == null) {
			list = new ArrayList<YHQInfo>();
			mListView.setVisibility(View.GONE);
			wan51_yhqlist_tx.setVisibility(View.VISIBLE);
			
		}else{
			other = list.get(0).getOther();
			mListView.setVisibility(View.VISIBLE);
			wan51_yhqlist_tx.setVisibility(View.GONE);
		}
		mListView.addFooterView(footerView);
		listAdapter = new YHlistAdapter();
		mListView.setAdapter(listAdapter);
		
		footer_tx = (TextView) footerView.findViewById(Util.getResID("wan_footer_tx", "id"));
		wan_footer_pro = (ProgressBar) footerView.findViewById(Util.getResID("wan_footer_pro", "id"));
		if("0".equals(other)){
			footer_tx.setText("没有更多优惠券了");
		}else if("1".equals(other)){
			footer_tx.setText("查看更多优惠券");
		}
		footer_tx.setOnClickListener(this);
		
		mListView.setOnItemClickListener(this);

		yhlist_dh_btn = (Button) findViewById(Util.getResID("yhlist_dh_btn",
				"id"));
		yhlist_dh_btn.setOnClickListener(this);
		yhq_edit_code = (EditText) findViewById(Util.getResID("yhq_edit_code",
				"id"));
		yhqlist_back_btn = (TextView) findViewById(Util.getResID(
				"yhqlist_back_btn", "id"));
		yhqlist_back_btn.setOnClickListener(this);
		yhq_rule_tx = (TextView) findViewById(Util
				.getResID("yhq_rule_tx", "id"));
		yhq_rule_tx.setOnClickListener(this);
	}

	class YHlistAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			if(list.size()>0){
				return list.get(position);
			}else {
				return null;
			}
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		class Holder {
			TextView yhqlist_number, yhqis, yhq_list_min_price, yhq_list_date,wan51_yhqlist_gamename;
			RelativeLayout yhqlist_img_rel;
			ImageView yhqlist_right_img;
			
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			YHQInfo yi = list.get(position);
			Holder holder = null;
			if (convertView == null) {
				convertView = View.inflate(WanYHListActivity.this,
						Util.getResID("wan51_yhq_list", "layout"), null);
				holder = new Holder();
				holder.yhqlist_number = (TextView) convertView
						.findViewById(Util.getResID("yhqlist_number", "id"));
				holder.yhqis = (TextView) convertView.findViewById(Util
						.getResID("order_yhq_is", "id"));
				holder.yhqlist_img_rel = (RelativeLayout) convertView
						.findViewById(Util.getResID("yhqlist_img_rel", "id"));
				holder.yhq_list_min_price = (TextView) convertView
						.findViewById(Util.getResID("yhq_list_min_price", "id"));
				holder.yhq_list_date = (TextView) convertView.findViewById(Util
						.getResID("yhq_list_date", "id"));
				holder.yhqlist_right_img = (ImageView) convertView
						.findViewById(Util.getResID("yhqlist_right_img", "id"));
				holder.wan51_yhqlist_gamename = (TextView) convertView.findViewById(Util.getResID("wan51_yhqlist_gamename", "id"));
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			
			holder.wan51_yhqlist_gamename.setText(yi.getGame()+"");
			holder.yhqlist_number.setText(yi.getPrice().substring(0, yi.getPrice().length()-3));
			int status = Integer.parseInt(yi.getStatus());
			switch(status){
			case 1:
				holder.yhqlist_img_rel.setBackgroundResource(Util.getResID(
						"yhq_img_bg", "drawable"));
				holder.yhqis.setText("可用");
				holder.yhqlist_right_img.setVisibility(View.VISIBLE);
				break;
			case 2:
				holder.yhqlist_img_rel.setBackgroundResource(Util.getResID(
						"yhq_img_bg", "drawable"));
				holder.yhqis.setText("不可用");
				holder.yhqlist_right_img.setVisibility(View.GONE);
				break;
			case 3:
				holder.yhqis.setText("已使用");
				holder.yhqlist_img_rel.setBackgroundResource(Util.getResID(
						"yhq_img_bg_low", "drawable"));
				holder.yhqlist_right_img.setVisibility(View.GONE);
				break;
			case 4:
				holder.yhqis.setText("已过期");
				holder.yhqlist_img_rel.setBackgroundResource(Util.getResID(
						"yhq_img_bg_low", "drawable"));
				holder.yhqlist_right_img.setVisibility(View.GONE);
				break;
			case 5:
				holder.yhqlist_img_rel.setBackgroundResource(Util.getResID(
						"yhq_img_bg", "drawable"));
				holder.yhqlist_right_img.setVisibility(View.GONE);
				holder.yhqis.setText("可用");
				break;
			}


			holder.yhq_list_min_price.setText("满" + yi.getMin_orice()
					+ "元可用");
			holder.yhq_list_date.setText("有效期至" + yi.getOff_data());
			return convertView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		YHQInfo yhqinfo = list.get(arg2);
		
		int status = Integer.parseInt(yhqinfo.getStatus());
		switch(status){
		case 1:
			payInfo.setYhqInfo(yhqinfo);
			Intent intent = new Intent(WanYHListActivity.this,
					Pay_Order_Activity.class);
			intent.putExtra("payinfo", payInfo);
			startActivity(intent);
			finish();
			break;
		case 2:
			Toast.makeText(getApplicationContext(), "充值金额不符合",
					Toast.LENGTH_SHORT).show();

			break;
		case 3:
			Toast.makeText(getApplicationContext(), "优惠券已使用",
					Toast.LENGTH_SHORT).show();
			break;
		case 4:
			Toast.makeText(getApplicationContext(), "优惠券已过期",
					Toast.LENGTH_SHORT).show();
			break;
		case 5:
			Toast.makeText(getApplicationContext(), "优惠券已冻结",
					Toast.LENGTH_SHORT).show();
			break;
		case 6:
			
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == Util.getResID("yhlist_dh_btn", "id")) {
			yhq_code = yhq_edit_code.getText().toString();
			YHQCodeTask yhqCode = new YHQCodeTask();
			yhqCode.execute();
			//
		} else if (v.getId() == Util.getResID("yhqlist_back_btn", "id")) {
			Intent intent = new Intent(WanYHListActivity.this,
					Pay_Order_Activity.class);
			intent.putExtra("payinfo", payInfo);
			startActivity(intent);
			finish();
		} else if (v.getId() == Util.getResID("yhq_rule_tx", "id")) {
			Intent intent = new Intent(WanYHListActivity.this,
					WANRuleActivity.class);
			startActivity(intent);
		}else if(v.getId() == Util.getResID("wan_footer_tx", "id")){
			if("0".equals(other)){
				Toast.makeText(getApplicationContext(), "没有更多优惠券", Toast.LENGTH_SHORT).show();
			}else if("1".equals(other)){
//				footer_tx.setText("查看更多优惠券");
				footer_tx.setVisibility(View.GONE);
				wan_footer_pro.setVisibility(View.VISIBLE);
				page = page+1;
				PayYHQTask paytask = new PayYHQTask(payInfo,page);
				paytask.setYhqListener(morder_yhqlistener);
				paytask.execute();
			}
		}
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent(WanYHListActivity.this,
					Pay_Order_Activity.class);
			intent.putExtra("payinfo", payInfo);
			startActivity(intent);
			finish();
		}
		return false;
	}

	private PayOrderYHQTaskListener morder_yhqlistener = new PayOrderYHQTaskListener() {

		@Override
		public void yhq_result(Object object) {
			ArrayList<YHQInfo> liste = (ArrayList<YHQInfo>) object;
			footer_tx.setVisibility(View.VISIBLE);
			wan_footer_pro.setVisibility(View.GONE);
			if (liste != null && liste.size() > 0) {
				
				mListView.setVisibility(View.VISIBLE);
				
				
				
				list.addAll(liste);
				
				other = list.get(list.size()-1).getOther();
				listAdapter.notifyDataSetChanged();
				if("0".equals(other)){
					footer_tx.setText("没有更多优惠券了");
				}else if("1".equals(other)){
					footer_tx.setText("查看更多优惠券");
				}
				
			} else {
				
			}
		}

		@Override
		public void payOrderid(PayInfo payinfo, String orderid) {
			// TODO Auto-generated method stub

		}
	};

	class YHQCodeTask extends AsyncTask {
		String urlpath = Conet.YHQCodeUrl;
		String state;
		@Override
		protected Object doInBackground(Object... params) {

			String time = System.currentTimeMillis() + "";
			int tim = (int) (Long.parseLong(time) / 1000);
			String auth = Conet.mWanAppInfo.getPlatformgid() + 19
					+ Conet.mUserInfo.getUser_id() + tim + "#"
					+ "8#37@2454A227f##@72240@8b3Ad7367";

			String auths = MD5Utils.getMD5(auth);
			;
			
			String encodeStr = URLEncoder.encode(Conet.mUserInfo.getUser_name());
			String baseStr = Base64.encodeBytes(encodeStr.getBytes());
			
			String url = urlpath + "&gameid="
					+ Conet.mWanAppInfo.getPlatformgid() + "&channelid="
					+ 19 + "&userid=" + Conet.mUserInfo.getUser_id()
					+ "&time=" + tim + "&auth=" + auths + "&giftcode="
					+ yhq_code + "&username=" + baseStr;
			// giftcode
			// gameid
			// channelid
			// username
			// userid
			// time
			// auth
			HttpGet httpGet = new HttpGet(url);
			try {

				HttpResponse httpResponse = new DefaultHttpClient()
						.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					String strResult = EntityUtils.toString(
							httpResponse.getEntity(), "UTF-8");
					String ss = strResult;
					JSONObject jsonObject = new JSONObject(ss);
					state = jsonObject.getString("state");	
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			// gameid
			// channelid
			// username
			// userid
			// time
			// auth
			// money
			return null;
		}
		
		@Override
		protected void onPostExecute(Object result) {
			if ("1".equals(state)) {
				page = 1;
				list.clear();
				PayYHQTask paytask = new PayYHQTask(payInfo,page);
				paytask.setYhqListener(morder_yhqlistener);
				paytask.execute();
				Toast.makeText(getApplicationContext(), "兑换成功", Toast.LENGTH_SHORT).show();
			}else if("-6".equals(state)){
				Toast.makeText(getApplicationContext(), "未激活", Toast.LENGTH_SHORT).show();
			}else if("-7".equals(state)){
				Toast.makeText(getApplicationContext(), "已被兑换", Toast.LENGTH_SHORT).show();
			}else if("-7".equals(state)){
				Toast.makeText(getApplicationContext(), "已被兑换", Toast.LENGTH_SHORT).show();
			}else if("-8".endsWith(state)){
				Toast.makeText(getApplicationContext(), "兑换券已被使用", Toast.LENGTH_SHORT).show();
			}else if("-9".endsWith(state)){
				Toast.makeText(getApplicationContext(), "礼券已被冻结", Toast.LENGTH_SHORT).show();
			}else if("-10".endsWith(state)){
				Toast.makeText(getApplicationContext(), "礼券码已过期", Toast.LENGTH_SHORT).show();
			}else if("-11".endsWith(state)){
				Toast.makeText(getApplicationContext(), "不符合游戏", Toast.LENGTH_SHORT).show();
			}else if("-12".endsWith(state)){
				
			}else{
				Toast.makeText(getApplicationContext(), "兑换码错误", Toast.LENGTH_SHORT).show();
			}
		}
	}
}
